import downloadCsv from 'download-csv';

let cpu = '', gpu = ''
let pageTitle;

// chrome.local.storage获cpu、gpu   
chrome.storage.local.get({ cpu: "", gpu: "" }, function (item) {
    cpu = item.cpu;
    gpu = item.gpu;
    document.getElementsByName('cpu')[0].innerText = cpu;
    document.getElementsByName('gpu')[0].innerText = gpu;
});

// 向 background 发送自己的 tabId
chrome.tabs.query({
    active: true,
    currentWindow: true
}, (tabs) => {
    chrome.runtime.sendMessage(
        { type: 'VIEW_TAB_ID', viewTabId: tabs[0].id }
    );
});

let records = [];

// echarts
let chartDom = document.getElementById('chart');
let myChart = echarts.init(chartDom);

// 接收来自 background 的监控记录
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'RECORD') {
        let { time, currFPS, currMEM, title } = request.payload;
        if (pageTitle === undefined) {
            pageTitle = title;
        }
        records.push({ time, currFPS: Math.round(currFPS), currMEM: Math.round(currMEM) })

        let timeArr = records.map(x => x.time),
            fpsArr = records.map(x => x.currFPS),
            memArr = records.map(x => x.currMEM);

        document.getElementById('page-title').innerText = pageTitle;
        document.getElementById('currFPS').innerText = fpsArr[fpsArr.length - 1];
        document.getElementById('avgFPS').innerText = Math.round(fpsArr.reduce((acc, val) => acc + val, 0) / fpsArr.length);
        document.getElementById('currMEM').innerText = memArr[memArr.length - 1];
        document.getElementById('maxMEM').innerText = Math.max.apply(null, memArr);
        myChart.setOption(getOptions(timeArr, fpsArr, memArr));

        // 判断是否上传到服务器
        chrome.storage.local.get({ upload: false }, function (item) {
            if (item.upload) {
                $.ajax({
                    type: "POST",
                    url: "http://106.75.166.136:31205/record",
                    data: JSON.stringify({ cpu, gpu, page_title: pageTitle, fps: currFPS, mem: currMEM }),
                    contentType: "application/json",
                    dataType: "json",
                });
            }
        });
    }
});

/**
 * 获取echarts的配置项
 * @param {Array} timeArr 时间序列
 * @param {Array} fpsArr fps序列
 * @param {Array} memArr 内存序列
 * @returns 
 */
function getOptions(timeArr, fpsArr, memArr) {
    return {
        tooltip: { trigger: 'axis' },
        grid: { left: '5%', right: '5%', bottom: '5%', top: '10%' },
        legend: { data: ['帧率', '内存(M)'] },
        xAxis: {
            type: 'category',
            data: timeArr,
            axisLabel: { show: false }
        },
        yAxis: [
            { positon: 'left', type: 'value', name: '帧率' },
            { positon: 'right', type: 'value', name: '内存(M)' },
        ],
        series: [
            {
                yAxisIndex: 0,
                name: '帧率',
                type: 'line',
                data: fpsArr,
            },
            {
                yAxisIndex: 1,
                name: '内存(M)',
                type: 'line',
                data: memArr,
            }
        ]
    };
}

// 更改页面标题
document.getElementsByName('save-title')[0].addEventListener('click', function () {
    pageTitle = document.getElementById('pTitle').value;
});

// 点击下载
document.getElementById('download').addEventListener('click', function () {
    downloadCsv(records, { time: '时间', currFPS: 'FPS', currMEM: '内存' });
});